/*
 * Game.cc
 *
 *  Created on: Jan 9, 2013
 *      Author: Zermingore
 */

#include "Game.hh"
#include "common/stl.h"
#include "media/Sound.hh"
#include "input/Input.hh"


Game::Game() :
    _frameRate(1.0f / 60.0f), // 60 fps max
    _start(0),
    _end(0),
    _elapsed(0)
{
    _scene = new Scene();
    _input = new Input();
}

Game::~Game()
{
    // sound
    // alDeleteSources(1, &soundSource);
    // alDeleteBuffers(1, &soundBuffer);
    // alcDestroyContext(soundContext);
}


void Game::limitFramerate()
{
    // frame rate limit
    _end = _start;
    _start = glfwGetTime();

    if ((_elapsed = _start - _end) < _frameRate)
        glfwSleep(_frameRate - _elapsed);
}

void Game::playSound()
{
    // we'll need a Sound Manager
    #ifdef DEBUG_SOUND
        int* mouseX = new (int);
        int* mouseY = new (int);
        glfwGetMousePos(mouseX, mouseY);

        if (glfwGetKey(GLFW_KEY_SPACE) == GLFW_PRESS)
        {
            sound.setListenerPosition(Coords(*mouseX, *mouseY, 0));
            sound.play();
        }
    #endif
}


int Game::play()
{
    _scene->init(); //

    // Sound // TODO move in a Sound Manager
    Sound sound("sample.wav"); // TODO rm

    // game loop
    while (!_input->quit())
    {
        limitFramerate();
        loop();
        glfwSwapBuffers(); // auto poll events
    }

    return 0;
}


int Game::loop()
{
    _scene->draw();
    _input->treatEvent();
    playSound();

    return 0;
}
